﻿using CommonBase.ResponseBase;
using CustomControls.PoptipCtr.Base;
using LogProjectManager;
using ManagementToolClient.Models;
using Newtonsoft.Json;
using Prism.Commands;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using ManagementToolClient.BaseViewModels;
using Prism.Common;
using System.Windows;
using System.Collections.ObjectModel;
using CustomControls.PoptipCtr;

namespace ManagementToolClient.ViewModels
{
    internal class AddDeviceModuleViewModel : MiddleDalogViemModelBase, ILayDialogWindowAware
    {
        public new event Action<ILayDialogResult> RequestClose;

        private string DeviceID { set; get; }

        #region Property
        private ObservableCollection<ModuleManagerModel> _ModulesList;

        public ObservableCollection<ModuleManagerModel> ModulesList
        {
            get { return _ModulesList; }
            set
            {
                SetProperty(ref _ModulesList, value);

            }
        }

        private ModuleManagerModel _ModuleManagerItem;

        public ModuleManagerModel ModuleManagerItem
        {
            get { return _ModuleManagerItem; }
            set
            {
                SetProperty(ref _ModuleManagerItem, value);

            }
        }
        #endregion


        #region cmd
        private DelegateCommand _CloseCommand;
        public DelegateCommand CloseCommand =>
            _CloseCommand ?? (_CloseCommand = new DelegateCommand(ExcuteCloseCommand));



        private DelegateCommand _OKxCommand;
        public DelegateCommand OKxCommand =>
            _OKxCommand ?? (_OKxCommand = new DelegateCommand(ExcuteOKxCommand));




        #endregion



        public new bool CanCloseDialog()
        {
            return true;
        }

        public new void OnDialogClosed()
        {

        }



        public void OnDialogOpened(ILayDialogParameter parameters)
        {
            DeviceID=parameters.GetValue<string>("uuid");
            ModulesList = new ObservableCollection<ModuleManagerModel>();
            GetAllModules();
        }

        private void ExcuteCloseCommand()
        {
            BackPageCommandMethod(ButtonResult.No);
        }

        private void ExcuteOKxCommand()
        {
            if (ModuleManagerItem==null) 
            {
                return;
            }
            Task.Run(async () => {
                try
                {
                    var url = "http://127.0.0.1:8081" + "/api/ToAddDeviceModule?" + $"_devieid={DeviceID}" + "&" + $"_moduleid={ModuleManagerItem.uuid}" + "&" + $"_modulename={ModuleManagerItem.modulename}";


                    var httpClient = new System.Net.Http.HttpClient();
                    HttpContent content = new StringContent("", Encoding.UTF8, "application/json");

                    var response = httpClient.PostAsync(url, content).Result;
                    if (response.StatusCode == HttpStatusCode.OK)
                    {
                        string responseBody = await response.Content.ReadAsStringAsync();
                        var _itemResult = JsonConvert.DeserializeObject<AuthorizationCodeResponseBody>(responseBody);
                        if (_itemResult.code == ((int)ErrorCode.OK).ToString())
                        {
                            BackPageCommandMethod(ButtonResult.Yes);
                        }
                        else
                        {
                            MessageControl.Warning(_itemResult.Description, "RootMessageTooken");
                            LogManager.WriteLog(LogTypeEnum.Normal, "ExcuteOKxCommand", "新增失败");
                        }

                    }
                    else
                    {
                        LogManager.WriteLog(LogTypeEnum.Exception, "ExcuteOKxCommand", "接口访问失败");
                    }
                }
                catch (Exception ex)
                {
                    LogManager.WriteLog(LogTypeEnum.Exception, "GetDate", ex.Message);
                }
            });
        }


        private void BackPageCommandMethod(ButtonResult itemResult)
        {
            LayDialogResult dialogResult = new LayDialogResult();
            dialogResult.Result = itemResult;
            RequestClose?.Invoke(dialogResult);
        }

        private void GetAllModules() 
        {
            Task.Run(async () => {
                try
                {
                    var url = "http://127.0.0.1:8081" + "/api/GetAdllModule";

                    var httpClient = new System.Net.Http.HttpClient();


                    var response = httpClient.GetAsync(url).Result;
                    if (response.StatusCode == HttpStatusCode.OK)
                    {
                        string responseBody = await response.Content.ReadAsStringAsync();
                        var _itemResult = JsonConvert.DeserializeObject<AuthorizationCodeResponseBody>(responseBody);

                        if (_itemResult.code == ((int)ErrorCode.OK).ToString())
                        {
                            if (_itemResult.Data != null)
                            {
                                var itemList = JsonConvert.DeserializeObject<List<ModuleManagerModel>>(_itemResult.Data.ToString());
                                if (itemList.Count > 0)
                                {
                                    foreach (var item in itemList)
                                    {
                                        Application.Current.Dispatcher.Invoke(() => {
                                            ModulesList.Add(item);
                                        });
                                    }
                                }
                            }
                        }

                        else
                        {
                            LogManager.WriteLog(LogTypeEnum.Normal, "GetAllModules", "访问接口异常,data为空");
                        }

                    }
                    else
                    {
                        LogManager.WriteLog(LogTypeEnum.Exception, "GetAllModules", "接口访问失败");
                    }
                }
                catch (Exception ex)
                {
                    LogManager.WriteLog(LogTypeEnum.Exception, "GetDate", ex.Message);
                }
            });
        }
    }
}
